package com.dlc.felear.xiaoensale.dao;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.helper.CookingMenuMangerHelper;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.utils.TimeUtils;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CookingMenuDao {
    private static final String TAG = "CookingMenuDao";
    private Dao<CookingMenu, Integer> PipeInfoDao;
    private MenuFoodMaterialDao foodMaterialDao;
    private OperatorDao operatorDao;
    private Context context;

    /**
     * 构造方法
     * 获得数据库帮助类实例，通过传入Class对象得到相应的Dao
     *
     * @param context
     */
    public CookingMenuDao(Context context) {
        try {
            this.context = context;
            PipeInfoDao = DetailDataOpenHelper.getInstance(context).getDao(CookingMenu.class);
            operatorDao = new OperatorDao(context);
            foodMaterialDao = new MenuFoodMaterialDao(context);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public CookingMenu isExist(String name, String guige) {
        List<CookingMenu> list = queryForName1(name, guige);
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    public void addNewMenu(CookingMenu cookingMenu, String newId) {
        try {
            List<MenuFoodMaterial> flist = foodMaterialDao.queryForAllByCId(cookingMenu.getId());
            Log.e(TAG, " all flist:" + JsonHelper.toJson(foodMaterialDao.queryForAll(Constant.FOODS_TYPE_2)));
            List<Operator> olist = operatorDao.queryForAllByMID(cookingMenu.getId());
            if (flist == null || flist.isEmpty()) {
                Log.e(TAG, "addNewMenu flist为空");
                return;
            }
            if (olist == null || olist.isEmpty()) {
                Log.e(TAG, "addNewMenu olist为空");
                return;
            }
            cookingMenu.setUploaded(0);
            String sss = newId + "_" + cookingMenu.getMachineModoel();
            cookingMenu.setId(sss);
            cookingMenu.setUpdateTime(TimeUtils.getCurrrentTimeYMDHMS());
            PipeInfoDao.create(cookingMenu);
            operatorDao.addAll(olist, sss);
            foodMaterialDao.addAll(flist, sss);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    public void createOrUpdate(CookingMenu PipeInfo) {
        try {
            Log.e(TAG, "保存前：" + JsonHelper.toJson(PipeInfo));
            String newId = getId(PipeInfo.getId()) + "_" + PipeInfo.getMachineModoel() + PipeInfo.getSpecification();
            PipeInfo.setId(newId);
            if (queryById(PipeInfo.getId()) == null) {
                PipeInfoDao.create(PipeInfo);
            } else {
                PipeInfoDao.update(PipeInfo);
            }
            Log.e(TAG, "allData:" + JsonHelper.toJson(queryForAll()));
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    public void createOrUpdateAll(CookingMenu PipeInfo) {
        try {
            String newId = getId(PipeInfo.getId()) + "_" + PipeInfo.getMachineModoel() + PipeInfo.getSpecification();
            PipeInfo.setId(newId);
            createOrUpdate(PipeInfo);
            if (PipeInfo.getFoodMaterials() != null) {
                foodMaterialDao.addAll(PipeInfo.getFoodMaterials(), PipeInfo.getId());
            }
            if (PipeInfo.getOperators() != null) {
                operatorDao.addAll(PipeInfo.getOperators(), PipeInfo.getId());
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private String getId(String id) {
        int index = id.indexOf("_");
        if (index != -1) {
            return id.substring(0, index);
        }

        return id;
    }

    /**
     * 更新菜谱id
     *
     * @param oidId
     * @param newId
     */
    public void updateAllinfo(String oidId, String newId) {
        try {
            Log.e(TAG, "oldId=" + oidId + " newId=" + newId);
            CookingMenu PipeInfo = queryById(oidId);
            if (PipeInfo == null) {
                Log.e(TAG, "旧菜谱不存在");
                return;
            }
            newId = getId(newId) + "_" + PipeInfo.getMachineModoel() + PipeInfo.getSpecification();
            if (TextUtils.equals(PipeInfo.getId(), newId)) {
                Log.e(TAG, "该菜谱已存在");
                return;
            }
            PipeInfo.setUploaded(1);
            updateFoodM(PipeInfo.getId(), newId);
            updateOper(PipeInfo.getId(), newId);
            delete(PipeInfo);
            PipeInfo.setId(newId);
            PipeInfoDao.create(PipeInfo);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void updateOper(String oldId, String newId) {
        List<Operator> tempList = operatorDao.queryForAllByMID(oldId);
        if (tempList != null) {
            for (Operator operator : tempList) {
                operatorDao.delete(operator);
                operator.setmId(newId);
                operatorDao.add(operator);
            }
        }
        Log.e(TAG, "operators:" + JsonHelper.toJson(operatorDao.queryForAllByMID(newId)));
    }

    private void updateFoodM(String oldId, String newId) {
        List<MenuFoodMaterial> tempList = foodMaterialDao.queryForAllByCId(oldId);
        if (tempList != null) {
            for (MenuFoodMaterial operator : tempList) {
                foodMaterialDao.delete(operator);
                operator.setCid(newId);
                foodMaterialDao.addOrUpdate(operator);
            }
        }
        Log.e(TAG, "MenuFoodMaterial:" + JsonHelper.toJson(foodMaterialDao.queryForAllByCId(newId)));
    }


    public void addAll(List<CookingMenu> list) {
        if (list == null) {
            return;
        }
        for (CookingMenu CookingMenu : list) {
            createOrUpdate(CookingMenu);
        }
    }

    /**
     * 删除一条记录
     *
     * @param PipeInfo
     */
    public void delete(CookingMenu PipeInfo) {
        try {
            CookingMenuMangerHelper.getInstance(context, this).removeMenuInfo(PipeInfo);
            Log.e(TAG, "delete name" + PipeInfo.getName());
            PipeInfoDao.delete(PipeInfo);
        } catch (Exception e) {
            Log.e(TAG, "delete Exception" + e.getMessage());
        }
    }

    public void deleteAllInfo(CookingMenu PipeInfo) {
        try {
            Log.e(TAG, "删除:" + PipeInfo.getName());
            delete(PipeInfo);
            if (foodMaterialDao != null) {
                foodMaterialDao.deleteForCid(PipeInfo.getId());
            }
            if (operatorDao != null) {
                operatorDao.deleteByCid(PipeInfo.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteAll() {
        try {
            deletes(queryForAll());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deletes(List<CookingMenu> data) {
        if (data == null || data.isEmpty()) {
            return;
        }
        for (CookingMenu PipeInfo : data) {
            deleteAllInfo(PipeInfo);
        }
    }

    public void deletesAll(int upload) {
        List<CookingMenu> data = queryForAll();
        if (data == null || data.isEmpty()) {
            return;
        }
        for (CookingMenu PipeInfo : data) {
            if (PipeInfo.getUploaded() == 1) {
                deleteAllInfo(PipeInfo);
            }
        }
    }

    /**
     * 查询一条记录
     *
     * @param name
     * @return
     */
    public List<CookingMenu> queryForLikeName(String name) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder().where().like("name", "%" + name + "%").query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfo;
    }

    public List<CookingMenu> queryForName(String name, int type) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder().where().eq("name", name).and()
                    .eq("type", type)
                    .query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfo;
    }

    public List<CookingMenu> queryForName(String name) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder().where().eq("name", name)
                    .query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfo;
    }

    public List<CookingMenu> queryForNameLeve(String name, int level) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder()
                    .orderBy("name", false)
                    .where()
                    .eq("name", name)
                    .and()
                    .eq("level", Integer.toString(level))
                    .query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfo;
    }

    public List<CookingMenu> queryForNameByType(String name, int level) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder()
                    .orderBy("name", false)
                    .where()
                    .eq("name", name)
                    .and()
                    .eq("type", level)
                    .query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfo;
    }

    public List<CookingMenu> queryForMacNo(String name) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder().where().eq("mac_no", name).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfo;
    }

    private List<CookingMenu> queryForName1(String name, String guige) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder()
                    .where()
                    .eq("name", name)
                    .and()
                    .eq("specification", guige)
                    .query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfo;
    }


    /**
     * 查询所有记录
     *
     * @return
     */
    public List<CookingMenu> queryForAll() {
        List<CookingMenu> PipeInfos = new ArrayList();
        try {
            PipeInfos = PipeInfoDao.queryBuilder()
                    .orderBy("name", false).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return PipeInfos;
    }

    /**
     * 根据类别 0普通 1餐厅标准菜谱
     *
     * @param levl
     * @return
     */
    public List<CookingMenu> queryForType(int levl) {
        List<CookingMenu> PipeInfos = new ArrayList();
        try {
            PipeInfos = PipeInfoDao.queryBuilder()
                    .orderBy("u_time", false)
                    .where().eq("type", levl)
                    .query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "data:" + JsonHelper.toJson(PipeInfos));
        return PipeInfos;
    }

    public CookingMenu queryById(String id) {
        List<CookingMenu> PipeInfo = null;
        try {
            PipeInfo = PipeInfoDao.queryBuilder().where().eq("id", id).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (PipeInfo == null || PipeInfo.isEmpty()) {
            return null;
        }
        return PipeInfo.get(0);
    }

    public void deleteMenu(String name, String machineModoel, String specification) {
        try {
            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(machineModoel) || TextUtils.isEmpty(specification)) {
                return;
            }
            List<CookingMenu> list = PipeInfoDao.queryBuilder()
                    .where().eq("name", name)
                    .and().eq("machineModoel", machineModoel)
                    .and().eq("specification", specification)
                    .query();
            if (list != null && !list.isEmpty()) {
                deletes(list);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
